"use strict";

const Controller = require("egg").Controller;

class DictController extends Controller {
  async index() {
    const { ctx } = this;
    try {
      // 获取分页参数（带默认值）
      const dict_name = ctx.query.dict_name && ctx.query.dict_name.trim();
      const dict_code = ctx.query.dict_code && ctx.query.dict_code.trim();
      const page = parseInt(ctx.query.page) || 1;
      const pageSize = parseInt(ctx.query.pageSize) || 10;
      const result = await ctx.service.dict.index(dict_name, dict_code, {
        page,
        pageSize,
      });
      // 返回标准化分页响应
      ctx.body = {
        success: true,
        code: 0,
        message: "获取字典类型列表成功",
        data: {
          list: result.rows,
          total: result.count,
        },
      };
    } catch (error) {
      // 特定异常处理
      if (error.name === "UnauthorizedError") {
        ctx.status = 401;
        ctx.body = {
          code: ctx.status,
          error: "AUTH_FAILED",
          message: error.message,
        };
        return;
      }
      // 其他错误处理
      ctx.status = 500;
      ctx.body = {
        code: ctx.status,
        message: "服务器内部错误",
        error: error.message,
      };
      return;
    }
  }

  async create() {
    const { ctx } = this;
    const dictData = ctx.request.body;
    // 参数校验
    try {
      ctx.validate(
        {
          dict_name: { type: "string", required: true, allowEmpty: false },
          dict_code: { type: "string", required: true, allowEmpty: false },
        },
        dictData
      );
    } catch (err) {
      ctx.status = 422;
      ctx.body = {
        code: ctx.status,
        message: "参数校验失败",
        errors: err.errors.map((e) => ({
          field: e.field,
          message: e.message,
        })),
      };
      return;
    }

    try {
      const newDict = await ctx.service.dict.create(dictData);
      ctx.status = 201; // Created
      ctx.body = {
        code: 0,
        success: true,
        message: "字典类型创建成功",
        data: newDict,
      };
    } catch (error) {
      // 特定异常处理
      if (error.name === "UnauthorizedError") {
        ctx.status = 401;
        ctx.body = {
          code: ctx.status,
          error: "AUTH_FAILED",
          message: error.message,
        };
        return;
      }
      // 其他错误处理
      ctx.status = 500;
      ctx.body = {
        code: ctx.status,
        message: "服务器内部错误",
        error: error.message,
      };
      return;
    }
  }

  async destroy() {
    const { ctx } = this;
    const id = ctx.params.id;

    // 参数校验
    if (!id || isNaN(id)) {
      ctx.status = 400;
      ctx.body = { code: 400, message: "无效的字典类型ID" };
      return;
    }

    // 1. 检查该字典类型下是否存在关联的字典数据
    const hasData = await ctx.service.dictItem.countByTypeId(id);

    // 2. 如果存在关联数据，阻止删除
    if (hasData > 0) {
      ctx.status = 400;
      ctx.body = {
        code: 400,
        success: false,
        message: "该字典类型下存在关联数据，无法删除",
      };
      return;
    }

    try {
      const result = await ctx.service.dict.destroy(id);
      if (result) {
        ctx.body = {
          code: 0,
          success: true,
          message: "字典类型删除成功",
        };
      } else {
        ctx.status = 404;
        ctx.body = { code: 404, message: "字典类型未找到" };
      }
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: "服务器内部错误",
        error: error.message,
      };
    }
  }

  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const dictData = ctx.request.body;

    // 参数校验
    if (!id || isNaN(id)) {
      ctx.status = 400;
      ctx.body = { code: 400, message: "无效的字典类型ID" };
      return;
    }
    try {
      ctx.validate(
        {
          dict_name: { type: "string", required: true, allowEmpty: false },
          dict_code: { type: "string", required: true, allowEmpty: false },
        },
        dictData
      );
    } catch (err) {
      ctx.status = 422;
      ctx.body = {
        code: ctx.status,
        message: "参数校验失败",
        errors: err.errors.map((e) => ({
          field: e.field,
          message: e.message,
        })),
      };
      return;
    }
    try {
      const updatedDict = await ctx.service.dict.update(id, dictData);
      if (updatedDict) {
        ctx.body = {
          code: 0,
          success: true,
          message: "字典类型更新成功",
          data: updatedDict,
        };
      } else {
        ctx.status = 404;
        ctx.body = { code: 404, message: "字典类型未找到" };
      }
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: "服务器内部错误",
        error: error.message,
      };
    }
  }

  async dictItemsByDictCode() {
    const { ctx } = this;
    try {
      // 获取分页参数（带默认值）
      const dict_code = ctx.query.dict_code && ctx.query.dict_code.trim();
      const result = await ctx.service.dict.dictItemsByDictCode(dict_code);
      // 返回标准化分页响应
      ctx.body = {
        success: true,
        code: 0,
        message: "获取字典数据成功",
        data: result,
      };
    } catch (error) {
      // 特定异常处理
      if (error.name === "UnauthorizedError") {
        ctx.status = 401;
        ctx.body = {
          code: ctx.status,
          error: "AUTH_FAILED",
          message: error.message,
        };
        return;
      }
      // 其他错误处理
      ctx.status = 500;
      ctx.body = {
        code: ctx.status,
        message: "服务器内部错误",
        error: error.message,
      };
      return;
    }
  }
}

module.exports = DictController;
